/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Classes;

import java.io.*;
import java.net.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 *
 * @author ward
 */
public class OpenProjectToXML extends HttpServlet {
   
    AE.VarParams varParams;
    AE.DataConsolidation dc;
    AE.MyListString projectItems;    
    AE.Data analysisProject;

    /** 
    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = null;
        try {
            // this is to be an entry in the web.xml file that points to a drive/subdir
            // where variables.config and license.config reside
            String FullySpecifiedPathToBaseDirectoryOfFiles =
                    getServletContext().getInitParameter( "OpenProjectToXML" );
            String sessionId = request.getSession().getId();
            
            out = response.getWriter();
            if( out != null )
            {
                String errMsg = Init( FullySpecifiedPathToBaseDirectoryOfFiles, sessionId );
                if( errMsg != null )
                    out.write( errMsg );
                else
                {
                    out.println( "<?xml version='1.0' encoding='Windows-1252'?>" );

                    String xslFile;
                    xslFile =  request.getParameter( "xslFile" );
                    if( xslFile != null )
                        out.write( String.format( "<?%s type='text/xsl' href='%s' ?>", "xml-stylesheet", xslFile ) );
                    
                    out.println( "<Projects>" );
                    
                    String fileName = request.getParameter("uploadedProjectFile");
                    if( fileName != null )
                    {
                        AE.MyListString lines = new AE.MyListString();
                        try
                        {
                            BufferedReader input ;
                            input = new BufferedReader( new FileReader( fileName ));
                            if( input != null )
                            {
                                String line = null;
                                while (( line = input.readLine()) != null)
                                {
                                    lines.Add( line );
                                }
                                input.close();
                            }
                            RunScriptCommandsToXML( out, lines );
                        } catch( IOException e ){}                             
                    }
                    else
                    {
                        RunAllProjectFilesToXML( out );
                    }

                    out.println( "</Projects>" );
                }
            }
        } catch( Exception e )
        {
            if( out != null )
                out.print( e.getLocalizedMessage() );
        } finally
        {
            if( out != null )
                out.close();
        }
    } 
    public void RunAllProjectFilesToXML( PrintWriter out )
    {
        AE.MyListString filelist = AE.MyDirectory.GetFiles( varParams.GetMyProjectsDir() );

        for( int projectIndex = 0,  projectCount = filelist.GetCount() ;
                projectIndex < projectCount ; projectIndex++ )
        {
            String projectFileName = filelist.Get( projectIndex );
            if( projectFileName.startsWith( "_" ) == false )
            {
                RunProjectFileToXML( out, projectFileName );
            }
        }
    }

    private void RunProjectFileToXML( PrintWriter out, String projectFileName )
    {
        String error = LoadProjectFromProjectFile( projectFileName );
        if( error != null )
            out.print( "There was a problem building this project. " + error );
        
        else
        {
            error = ExecuteProjectLines();
            if( error != null )
                out.print( error );
            else
                OutputXml.RunExecutedProjectToXml( out, projectFileName, analysisProject );
        }
    }

    private void RunScriptCommandsToXML( PrintWriter out, AE.MyListString projectItems )
    {
        String error = ExecuteProjectLines();
        if( error != null )
            out.print( error );
        else
            OutputXml.RunExecutedProjectToXml( out, null, analysisProject );
    }
    
    public String LoadProjectFromProjectFile( String projectFileName )
    {
        if( projectFileName == null || projectFileName.length() == 0 )
        {
            return "Invalid project filename";
        }
        
        String fullProjectFileName = varParams.GetMyProjectsDir() + projectFileName;
        if( AE.MyFile.Exists( fullProjectFileName ) == false )
        {
            return fullProjectFileName + " not found";
        } 
        
        projectItems = AE.MyFile.ReadAllLines( varParams, fullProjectFileName );
        if( projectItems == null || projectItems.GetCount() == 0 )
            return "problem with contents of " + fullProjectFileName;
        else
            return null;
    }

    private String ExecuteProjectLines()
    {
        analysisProject = new AE.Data();
        if( analysisProject == null )
            return "Failed to load, probably low memory or corrupted files" ;

        for( Integer i=0, count = projectItems.GetCount() ; i < count ; i++ )
        {
            String scriptItem = projectItems.Get( i );
            String message = ExecuteLine( scriptItem ) ;
            if( message != null )
                return "Line " + i.toString() + message ;
        }
        return null;    // a return value of null means success 
    }
    
    private String ExecuteLine( String scriptItem )
    {
        boolean success = dc.RunScript( scriptItem, analysisProject, true );
        if( success == false )
            return " failed: " + scriptItem;
        else
            return null;
    }

    public String Init( String variablesPath, String sessionId )
    {
        varParams = new AE.VarParams();
        if( varParams == null )
            return "Failed to load, probably low memory or corrupted files" ;

        String errMsg = varParams.ReadFile( variablesPath, sessionId );
        if( errMsg != null )
            return errMsg;

        dc = new AE.DataConsolidation( varParams );

        return null;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
    * Returns a short description of the servlet.
    */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
